package com.gitee.feizns.quickstart.web.resolver;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gitee.feizns.quickstart.web.resolver.annotation.Json;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * Json参数解析器
 * @author feizns
 * @since 2019/7/14
 */
public class JsonParameterResolver implements HandlerMethodArgumentResolver {

    /**
     * @see ObjectMapper
     */
    private final ObjectMapper objectMapper;

    public JsonParameterResolver(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(Json.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String jsonVal = webRequest.getParameter(parameter.getParameter().getName());
        return objectMapper.readValue(jsonVal, objectMapper.constructType(parameter.getGenericParameterType()));
    }

}